package com.fan.txl.ui;

import android.content.Intent;
import android.database.Cursor;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.base.txl.utils.RxUtils;
import com.fan.txl.R;
import com.fan.txl.data.contact.Contact;
import com.fan.txl.data.feed.Feed;
import com.fan.txl.databinding.ActivityDesignBinding;
import com.fan.txl.mock.api.service.FeedsService;
import com.fan.txl.ui.base.BaseActivity;
import com.fan.txl.ui.routers.ComponentRouters;
import com.fan.txl.vm.feeds.DesignVM;
import com.github.mzule.activityrouter.annotation.Router;
import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.util.concurrent.TimeUnit;
import io.reactivex.BackpressureStrategy;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.disposables.Disposable;
import io.reactivex.disposables.Disposables;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import io.realm.Realm;
import io.realm.RealmChangeListener;


/**
 * @title 输入内容提交
 */

@Router({ComponentRouters.design,})
//value = "item", longParams = "id", transfer = "id=>itemId
public class DesignUI extends BaseActivity {
     final int PICK_CONTACT_REQUEST=7425;

    ActivityDesignBinding mBinding;

    Feed mFeed = new Feed();


    //Feeds
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Contact _contact= getIntent().getParcelableExtra("data");
        if (_contact==null){
            _contact = new Contact();

            _contact.setMobile("15108280908");
            _contact.setName("张安");
        }
        mFeed.setFeedName(_contact.getName());
        mFeed.setFeedMobile(_contact.getMobile());

        mBinding= DataBindingUtil.setContentView(this,R.layout.activity_design);
        setSupportActionBar(mBinding.toolbar);
        //DesignVM designVM   = new DesignVM(mBinding,this);

        mBinding.toolbar.setTitle("评价朋友");
        mBinding.toolbar.setVerticalFadingEdgeEnabled(true);
        mBinding.setFeed(mFeed);


        RxView.clicks(mBinding.contentDesign.friend)
                .throttleFirst(300, TimeUnit.MILLISECONDS)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                            pickContact();
                    }
                });

    }

    private io.reactivex.Flowable<Realm> getRealm() {
        return io.reactivex.Flowable.create(new FlowableOnSubscribe<Realm>() {
            @Override
            public void subscribe(final FlowableEmitter<Realm> e) throws Exception {
               final Realm observableRealm = Realm.getDefaultInstance();
                final RealmChangeListener<Realm> listener  =new RealmChangeListener<Realm>() {
                    @Override
                    public void onChange(Realm element) {
                        e.onNext(element);
                    }
                };
                e.setDisposable(Disposables.fromRunnable(new Runnable() {
                    @Override
                    public void run() {
                        observableRealm.removeChangeListener(listener);
                        observableRealm.close();
                    }
                }));
                observableRealm.addChangeListener(listener);
                e.onNext(observableRealm);
            }
        },BackpressureStrategy.LATEST);
    }






    private void combine(){
        Observable<CharSequence> _fairChangeObservable = RxTextView.textChanges(mBinding.contentDesign.feeds).skip(1);
        //Observable<CharSequence> _fairChangeObservable = RxTextView.textChanges(emojiEditText).skip(1);

        //Observable.combineLatest(_fairChangeObservable,)
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.options_menu_design, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId= item.getItemId();
        switch (itemId){
            case R.id.action_send:
                onActionSend();
                break;
        }
        return true;
    }

    private void onActionSend(){
        mFeed.setWhereIs("四川;成都;青羊区;清大街道120号");
        mFeed.setGeo("30.127,130.5684");
        Toast.makeText(this, mFeed.getFeed(), Toast.LENGTH_SHORT).show();
        String feeds= JSON.toJSONString(mFeed);
        getAPIService()
                .getRpcService()
                .rpc(FeedsService.methodCreate,FeedsService.service,feeds)
                .compose(RxUtils.<String>applySchedulers(RxUtils.IO_ON_UI_TRANSFORMER))
                .compose(this.<String>bindUntilEvent(ActivityEvent.STOP))
                .subscribe(new DisposableObserver<String>() {
                    @Override
                    public void onNext(String s) {
                        Toast.makeText(DesignUI.this, ""+s, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {

                    }
                });




        //rxbus flash data
        //backUp
       // Observable.just(mFeeds)//check data
      /*  Observable.create(new ObservableOnSubscribe<Feeds>() {
            @Override
            public void subscribe(ObservableEmitter<Feeds> e) throws Exception {

                //e.onNext(contact);
            }
        })
                .compose(RxUtils.<Feeds>applySchedulers(RxUtils.IO_ON_UI_TRANSFORMER))
                .compose(this.<Feeds>bindUntilEvent(ActivityEvent.STOP))

                .subscribe(new DisposableObserver<Feeds>() {
                    @Override
                    public void onNext(Feeds feeds) {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });*/
    }

    private void onQueryContact(final Uri uri){
        Contact contact= queryContact(uri);
        mFeed.setFeedMobile(contact.getMobile());
        mFeed.setFeedName(contact.getName());
        /*Observable.create(new ObservableOnSubscribe<Contact>() {
            @Override
            public void subscribe(ObservableEmitter<Contact> e) throws Exception {
                try{
                    Contact contact= queryContact(uri);
                    e.onNext(contact);
                }catch (Exception exe){
                    exe.printStackTrace();
                }
            }
        })
                .compose(RxUtils.<Contact>applySchedulers(RxUtils.IO_ON_UI_TRANSFORMER))
                .compose(this.<Contact>bindUntilEvent(ActivityEvent.STOP))
                .subscribe(new DisposableObserver<Contact>() {
                    @Override
                    public void onNext(Contact contact) {
                        mFeed.setFeedMobile(contact.getMobile());
                        mFeed.setFeedName(contact.getName());
                    }

                    @Override
                    public void onError(Throwable e) {
                            e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {
                        //finish();
                    }
                });*/
    }


    private Contact queryContact(Uri uri){
        String[] projection = { ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME };
        Cursor cursor = getContentResolver().query(uri, projection,
                null, null, null);
        cursor.moveToFirst();

        int numberColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
        String number = cursor.getString(numberColumnIndex);

        int nameColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
        String name = cursor.getString(nameColumnIndex);

        cursor.close();
        return  new Contact(number,name);
    }


    private void pickContact() {
        Intent pickContactIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
        pickContactIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
        startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==PICK_CONTACT_REQUEST){
            if (resultCode==RESULT_OK){
                Uri contactUri=data.getData();
                onQueryContact(contactUri);
            }else{
                Toast.makeText(this, "未选择用户", Toast.LENGTH_SHORT).show();
            }
        }
    }



}
